package cn.tedu.weibo.service.impl;

import cn.tedu.weibo.exception.ServiceException;
import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDTO;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.WeiboDetailVO;
import cn.tedu.weibo.pojo.vo.WeiboIndexVO;
import cn.tedu.weibo.response.StatusCode;
import cn.tedu.weibo.service.IWeiboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WeiboService implements IWeiboService {
    @Autowired
    WeiboMapper weiboMapper;
    @Override
    public void addNew(WeiboDTO weiboDTO) {
        Weibo weibo = new Weibo();//创建空微博对象
        BeanUtils.copyProperties(weiboDTO,weibo);//将DTO的值赋值给weibo对象
        weibo.setCreated(new Date());//设置微博发布时间
        int rows = weiboMapper.insert(weibo);//调用mapper层新增一条微博,接收影响行数
        if(rows==0){//如果影响的行数为0,说明操作失败,抛出业务层异常
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }
    }

    @Override
    public List<WeiboIndexVO> lisForIndex() {
        return weiboMapper.selectForIndex();
    }

    @Override
    public List<WeiboIndexVO> listForIndexByUserId(Long userId) {
        return weiboMapper.selectForIndexByUserId(userId);
    }

    @Override
    public void deleteById(Long id) {
        weiboMapper.deleteById(id);
    }

    @Override
    public WeiboDetailVO detailById(Long id) {
        return weiboMapper.detailById(id);
    }
}
